import { saveAs } from 'file-saver';
import * as XLSX from 'xlsx';

/**
 * 将 ECharts 数据转换为可用于导出的二维数组
 * @param {Object} opt - ECharts 的 option 对象
 * @returns {Array<Array<string|number>>} 二维数组
 */
function aggregateChartDataToAoA(opt) {
    var header = ['', ...opt.xAxis[0].data];
    var body = [];
    for (const serie of opt.series) {
        var temp = [serie.name, ...serie.data];
        body.push(temp);
    }
    return [header, ...body];
}

export class ChartOptionConfig {
    static generateOption(item, showToolbox, isTitle) {
        return {
            title: { text: item.title || '图表', show: isTitle },
            tooltip: { trigger: 'axis' },
            legend: { data: item.legend || [], padding: [10, 20], },
            grid: {
                containLabel: true,
                left: '5%',
                right: '5%',
                bottom: '5%',
                top: '10%',
            },
            toolbox: {
                show: showToolbox,
                feature: {
                    dataView: {
                        show: true,
                        title: '表格数据',
                        lang: ['表格数据：', '关闭', '导出Excel'],
                        contentToOption: (HTMLDomElement, opt) => {
                            const data = aggregateChartDataToAoA(opt);
                            const worksheet = XLSX.utils.aoa_to_sheet(data);
                            const workbook = XLSX.utils.book_new();
                            XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
                            const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
                            const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
                            saveAs(blob, `${item.title}.xlsx`);
                        },
                        optionToContent: (opt) => {
                            const axisData = opt.xAxis[0].data;
                            const series = opt.series;
                            let tdHeads = '<td style="padding: 0 10px"></td>';
                            for (let i = 0; i < series.length; i++) {
                                tdHeads += `<td style="padding: 0 10px">${series[i].name}</td>`;
                            }
                            let table = `<table id="${this.name}-table" border="1" class="table-bordered table-striped" style="width:100%;text-align:center"><tbody><tr>${tdHeads}</tr>`;
                            for (let i = 0; i < axisData.length; i++) {
                                let row = `<tr><td style="padding: 0 10px">${axisData[i]}</td>`;
                                for (let j = 0; j < series.length; j++) {
                                    const value = series[j].data[i];
                                    row += `<td>${value ? value.toFixed(2) : '-'}</td>`;
                                }
                                table += row + `</tr>`;
                            }
                            return table + '</tbody></table>';
                        }
                    },
                    saveAsImage: {}
                }
            },
            xAxis: { type: 'category', data: item.xAxis || [] },
            yAxis: item.yAxis || {},
            series: item.series.length === 0 ? item.series[0] : item.series
        };
    }

    static generateOptionPie(item, showToolbox, isTitle) {
        return {
            title: { text: item.title || '图表', show: isTitle },
            tooltip: { trigger: 'axis' },
            legend: { data: item.legend || [], padding: [10, 20], },
            grid: {
                containLabel: true,
                left: '5%',
                right: '5%',
                bottom: '5%',
                top: '10%',
            },
            toolbox: {
                show: showToolbox,
                feature: {
                    saveAsImage: {}
                }
            },
            series: item.seriesPie
        };
    }
}